<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加服务</title>
</head>
<body>
<nav class="breadcrumb"><i class="Hui-iconfont">&#xe67f;</i>
    首页
    <span class="c-gray en">&gt;</span>
    基础设置
    <span class="c-gray en">&gt;</span>
    服务组合配置
    <span class="c-gray en">&gt;</span>
    修改服务组合
</nav>
<div class="page-container">
    <div class="form-unit">服务项目树结构</div>
    <ul id="treeDemo2"  class="ztree"></ul>

    <div class="form-unit">基本信息</div>
    <form  method="post" class="form form-horizontal" id="merchant-serviceBag-form-edit">
        <input name="servicePackageId" value="" id="BasicServiceBagEditServicePackageId" style="display: none;"/>
        <input style="display: none;" id="serviceBag-editArray" name="list"/>
        <div class="form-group">
            <label class="control-label col-xs-4 col-sm-3"><span class="c-red"></span>服务组合名称：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="text" class="form-control" value="" placeholder="必填项" id="BasicServiceBagEditServiceName" name="servicePackageName">
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-xs-4 col-sm-3"><span class="c-red"></span>服务组合价格：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="text" class="form-control" value="" placeholder="必填项" name="price" id="BasicServiceBagEditPrice">
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-xs-4 col-sm-3"><span class="c-red"></span>打折价格：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <input type="text" class="form-control" value="" placeholder="必填项" name="discountPrice" id="BasicServiceBagEditDiscountPrice">
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-xs-4 col-sm-3"><span class="c-red"></span>服务组合类型：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <select name="serviceType" id="BasicServiceBagEditServiceType">
                    <option value="1" selected="selected">洗车</option>
                    <option value="2">美容</option>
                    <option value="3">维修</option>
                </select>
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-xs-4 col-sm-3">服务描述：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <textarea id="BasicServiceBagEditServicePackageDesc" name="servicePackageDesc" cols="85" rows="4" class="textarea valid" placeholder="请输入服务的描述..."></textarea>
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-xs-4 col-sm-3">图片上传：</label>
            <div class="formControls col-xs-4 col-sm-4">
                <div class="uploader-list-container">
                    <input id="editManageImg" name="file[]" multiple type="file" class="file-loading"/>
                </div>
            </div>
        </div>
        <div class="form-group">
            <div class="col-xs-8 col-sm-9 col-xs-offset-4 col-sm-offset-3">
                <input onclick="merchantBasicServiceBagEditFun.submitAnaysis();return false;" class="btn btn-primary radius" type="submit" value="&nbsp;&nbsp;提交&nbsp;&nbsp;"/>
            </div>
        </div>
    </form>
</div>
<script type="text/javascript">
    /*服务礼包，添加页面 merchantBasicServiceBagEditFun*/
    var merchantBasicServiceBagEditFun;

    merchantBasicServiceBagEditFun={
        init : function () {
            let _this = this;
            var servicePackageId = sessionStorage.getItem("serviceBag-servicePackageId");
            $("#BasicServiceBagEditServicePackageId").val(servicePackageId);

            _this.bootstrapvalidatorForm();
            //查询服务组合
            _this.serviccePackage(servicePackageId);
            //加载select2
            $("#BasicServiceBagEditServiceType").select2({
                width : '195px'
            });
            //设置选中的节点
            _this.loadTreeChecked(servicePackageId);

            $('#BasicServiceBagEditServiceType').on('select2:select', function (e) {
                let data = e.params.data;
                _this.serviceType(data.id);
            });

        },
        //提交
        submitAnaysis : function () {
            //bootstrap验证
            var bootstrapValidator = $("#merchant-serviceBag-form-edit").data('bootstrapValidator');
            bootstrapValidator.validate();
            if(bootstrapValidator.isValid())
                $("#merchant-serviceBag-form-edit").submit();
            else return;

            var treeObj = $.fn.zTree.getZTreeObj("treeDemo2");
            var nodes = treeObj.getCheckedNodes(true);//在提交表单之前将选中的checkbox收集
            var array = new Array();
            for (var i = 0; i < nodes.length; i++) {
                array.push(nodes[i].id);
            }
            $("#serviceBag-editArray").val(array);

            //将元转为分
            var temp = $("#merchant-serviceBag-form-edit").serializeArray();
            for(var i =0;i<temp.length;i++){
                if(temp[i].name == 'price'){
                    temp[i].value = temp[i].value*100;
                }
                if(temp[i].name == 'discountPrice'){
                    temp[i].value = temp[i].value*100;
                }
            }

            $.ajax({
                type: "GET",
                url: "biz/updateServicePackage",
                data: temp,
                dataType: "json",
                success: function(data){
                    //state为true，修改成功
                    if(data.state){
                        if (isChange) {//有图片上传的
                            extData = {"typeId": "service_package_id", "relateId": $("#BasicServiceBagEditServicePackageId").val()};
                            $("#editManageImg").fileinput("upload");
                        }
                        layer.msg(data.message, {icon: 1});
                        //关闭新增窗口
                        removeIframe();

                        //涮新一次
                        $('#basic-serviceBag').bootstrapTable("refresh");

                    }else {
                        layer.msg(data.message, {icon: 0});
                    }

                },
                error:function () {
                    alert("error");
                }
            });
        },
        //bootstrap验证
        bootstrapvalidatorForm: function () {
            $('#merchant-serviceBag-form-edit').bootstrapValidator({
                message: 'This value is not valid',
                excluded : [':disabled'],
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    servicePackageName: {
                        validators: {
                            notEmpty: {
                                message: '服务组合名称不能为空'
                            },
                            stringLength: {
                                min: 2,
                                max: 50,
                                message: '服务组合名称长度必须在2到50位之间'
                            }
                        }
                    },
                    price: {
                        validators: {
                            notEmpty: {
                                message: '服务组合价格不能为空'
                            },
                            regexp: {
                                regexp: /^((^([1-9]\d*))|^0)(\.\d{1,2})?$|(^[-]0\.\d{1,2}$)$/,
                                message: '服务单价格式不正确'
                            },
                            stringLength: {
                                min: 1,
                                max: 5,
                                message: '服务组合价格长度必须在1到5位之间'
                            }
                        }
                    },
                    discountPrice: {
                        validators: {
                            notEmpty: {
                                message: '打折价格不能为空'
                            },
                            regexp: {
                                regexp: /^((^([1-9]\d*))|^0)(\.\d{1,2})?$|(^[-]0\.\d{1,2}$)$/,
                                message: '打折价格格式不正确'
                            },
                            stringLength: {
                                min: 1,
                                max: 5,
                                message: '打折价格长度必须在1到5位之间'
                            }
                        }
                    }
                }
            });
        },
        //加载下方可选择的服务树
        serviceType: function (index) {
            $.ajax({
                type: "get",
                url: "biz/getServiceTree",
                data: {serviceType:index},
                async: false,
                dataType: "json",
                success: function (data) {
                    if(data.state){
                        var merchantAddSetting = {
                            check: {
                                enable: true
                            },
                            data: {
                                simpleData: {
                                    enable: true
                                }
                            }
                        };
                        $.fn.zTree.init($("#treeDemo2"), merchantAddSetting, data.data);
                        var treeObj = $.fn.zTree.getZTreeObj("treeDemo2");
                        treeObj.expandAll(true);
                        //父节点不能选择
                        var nodes = treeObj.transformToArray(treeObj.getNodes());
                        for (var i = 0, l = nodes.length; i < l; i++) {
                            if (nodes[i].id < 100) {
                                treeObj.setChkDisabled(nodes[i], true);
                            }
                        }

                    }

                },
                error: function () {
                    alert("error");
                }
            });
        },
        //查询服务组合
        serviccePackage: function (servicePackageId) {
            let _this = this;
            $.ajax({
                type: "GET",
                url: "biz/getOneServicePackage",
                data: {servicePackageId:servicePackageId},
                async: false,
                dataType: "json",
                success: function (data) {
                    if(data.state){
                        $("#BasicServiceBagEditServiceName").val(data.data.servicePackageName);
                        $("#BasicServiceBagEditPrice").val(data.data.price/100);
                        $("#BasicServiceBagEditDiscountPrice").val(data.data.discountPrice/100);
                        $("#BasicServiceBagEditServicePackageDesc").val(data.data.servicePackageDesc);
                        _this.serviceType(data.data.serviceType);

                        $("#BasicServiceBagEditServiceType").find("option[value = '"+data.data.serviceType+"']").attr("selected","selected");

                        var resList = data.data.imgList;
                        if (resList != null) {
                            var urlList = [];
                            for (var i = 0; i < resList.length; i++) {
                                urlList.push("files"+resList[i]["url"]);
                            }
                            $("#editManageImg").fileinput({
                                language: "zh", //设置语言
                                uploadUrl: "file/upload", //上传的地址
                                allowedFileExtensions: ["jpg", "png", "gif"],//接收的文件后缀
                                maxFileCount: 1,
                                initialCaption: "请上传一张服务图片",//文本框初始话value
                                showUpload: false,//是否显示上传按钮
                                showRemove: false,//是否显示删除按钮
                                showCaption: true,//是否显示输入框
                                browseClass: "btn btn-primary", //按钮样式
                                enctype: "multipart/form-data",
                                showPreview: true,
                                uploadAsync: false,//多图片一次上传
                                maxSize: 1024,//单位kb
                                allowedPreviewTypes: ["image"],
                                uploadExtraData: function () {
                                    return extData;
                                },
                                initialPreview: urlList,
                                initialPreviewAsData: true,
                                //deleteUrl: "file/upload",
                                overwriteInitial: false,
                                maxFileSize: 100
                            }).on("change", function (event) {
                                isChange = true;
                            });
                        }

                    }else {
                        layer.msg(data.message, {icon: 0});
                    }

                },
                error: function () {
                    alert("error");
                }
            });
        },
        //加载下方选中节点
        loadTreeChecked: function (servicePackageId) {
            $.ajax({
                type: "GET",
                url: "biz/loadServicePackageRel?servicePackageId=" + servicePackageId,
                dataType: "json",
                success: function (data) {
                    if(data.state){
                        //首先取消所有选中状态
                        var treeObj = $.fn.zTree.getZTreeObj("treeDemo2");
                        treeObj.checkAllNodes(false);
                        treeObj.cancelSelectedNode();

                        //获取所有节点的信息data
                        for (var i = 0; i < data.data.length; i++) {
                            var zTree = $.fn.zTree.getZTreeObj("treeDemo2");
                            var node = zTree.getNodeByParam("id", data.data[i].serviceId);
                            node.checked = true;
                            //设置选中之后，需要更新一次，否则无法选中该节点
                            zTree.updateNode(node);
                        }
                    }else {
                        layer.msg(data.message, {icon: 0});
                    }
                },
                error: function () {
                    alert("error");
                }
            });
        },
    };

    var extData;
    var isChange;

    merchantBasicServiceBagEditFun.init();
</script>
</body>
</html>